package com.chenfan.mcn.component;

import com.chenfan.mcn.controller.MicroServiceController;
import com.chenfan.mcn.extension.mybatisplus.BaseAssembler;
import com.chenfan.mcn.model.base.BaseQueryDTO;
import com.chenfan.privilege.common.config.SearchAuthority;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;

import java.io.IOException;
import java.lang.reflect.Type;

/**
 * RequestBody拦截器
 *
 * @author wulg
 * @date 2021-09-14
 **/
@ControllerAdvice(annotations = RestController.class)
public class GlobalRequestBodyAdvice implements RequestBodyAdvice {

    private final long DEFAULT_PAGE_NUM = 1L;

    private final long DEFAULT_PAGE_SIZE = 10L;

    @Override
    public boolean supports(MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        if(methodParameter == null || methodParameter.hasParameterAnnotation(SearchAuthority.class)) {
            return false;
        }
        Class<?> controllerClass = methodParameter.getContainingClass();
        if(controllerClass != null && MicroServiceController.class.isAssignableFrom(controllerClass)) {
            return false;
        }
        return true;
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
        return inputMessage;
    }

    @Override
    public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        if(body instanceof BaseAssembler) {
            //忽略公共入参
            ((BaseAssembler)body).ignore();
        } else if(body instanceof BaseQueryDTO){
            BaseQueryDTO baseQueryDTO = (BaseQueryDTO)body;
            baseQueryDTO.setPageNum(ObjectUtils.defaultIfNull(baseQueryDTO.getPageNum(), DEFAULT_PAGE_NUM));
            baseQueryDTO.setPageSize(ObjectUtils.defaultIfNull(baseQueryDTO.getPageSize(), DEFAULT_PAGE_SIZE));
        }
        return body;
    }

    @Override
    public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        return body;
    }
}
